import { v } from "convex/values"
import { defineSchema, defineTable, SearchFilter } from "convex/server"
import { mutation, query } from "./_generated/server";

export default defineSchema({
    boards: defineTable({
        title: v.string(),
        orgId: v.string(),
        authorId: v.string(),
        authorName: v.string(),
        imageUrl: v.string(),
    })
        .index("by_org", ["orgId"])
        .searchIndex("search_index", {
            searchField: "title",
            filterFields: ["orgId"],
        }),
    userFavorites: defineTable({
        orgId: v.string(),
        userId: v.string(),
        boardId: v.id("boards"),
    })
        .index("by_board", ["boardId"])
        .index("by_user_org", ["userId", "orgId"])
        .index("by_user_board", ["userId", "boardId"])
        .index("by_user_board_org", ["userId", "boardId", "orgId"])
})
// 定义一个用于将特定看板标记为收藏的mutation操作
export const favourite = mutation({
    // 定义mutation所需的参数
    args: {
        id: v.id("boards"),
        orgId: v.string()
    },
    // 定义mutation的处理程序
    handler: async (ctx, args) => {
        // 获取当前用户的认证信息
        const identity = await ctx.auth.getUserIdentity();

        // 如果未获取到用户身份信息，则抛出未授权错误
        if (!identity) {
            throw new Error("Unauthorized");
        }

        // 根据提供的id获取看板信息
        const board = await ctx.db.get(args.id);

        // 如果未找到看板，则抛出看板未找到错误
        if (!board) {
            throw new Error("Board not found");
        }

        // 获取当前用户的ID
        const userId = identity.subject;

        // 检查当前用户是否已经收藏了该看板
        const existingFavourite = await ctx.db
            .query("userFavorites")
            .withIndex("by_user_board", (q) =>
                q.eq("userId", userId).eq("boardId", board._id)
            )
            .unique();

        // 如果用户已经收藏了该看板，则抛出相应错误
        if (existingFavourite) {
            throw new Error("Board already favourited");
        }

        // 将看板添加到用户的收藏中
        await ctx.db.insert("userFavorites", {
            orgId: args.orgId,
            userId: userId,
            boardId: board._id,
        });

        // 返回收藏的看板信息
        return board;
    },
});

export const unfavourite = mutation({
    args: { id: v.id("boards") },
    handler: async (ctx, args) => {
        const identity = await ctx.auth.getUserIdentity();

        if (!identity) {
            throw new Error("Unauthorized");
        }

        const board = await ctx.db.get(args.id);

        if (!board) {
            throw new Error("Board not found");
        }

        const userId = identity.subject;

        const existingFavourite = await ctx.db
            .query("userFavorites")
            .withIndex("by_user_board", (q) =>
                q.eq("userId", userId).eq("boardId", board._id)
            )
            .unique();

        if (!existingFavourite) {
            throw new Error("Favorited board not found");
        }

        await ctx.db.delete(existingFavourite._id);

        return board;
    },
});

export const get = query({
    args: { id: v.id("boards") },
    handler: async (ctx, args) => {
        const board = await ctx.db.get(args.id);

        if (!board) {
            throw new Error("Board not found");
        }

        return board;
    },
});
